#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>

// 查看一个文件
void ls_file(char *file_name);
void ls_dir(char *dir_name);

int main(int argc, char *argv[])
{
    if (argc < 2) {
        ls_dir(".");
    } else {
        ls_file(argv[1]);
    }
    return 0;
}

void ls_dir(char *dir_name)
{
    DIR *fd = opendir(dir_name);

    struct dirent *mydirent;
    
    do {
        mydirent = readdir(fd);

        ls_file(mydirent->d_name);

    } while (mydirent);

    if (closedir(fd) == -1) {
        perror("closedir");
        return ;
    }
}


void ls_file(char *file_name)
{
    struct stat mystat;

    if (stat(file_name, &mystat) == -1){
        perror("stat");
        return ;
    }

    printf("mystat.st_mode = %o\n", mystat.st_mode);
    return;

    switch (mystat.st_mode & __S_IFMT) {
        case __S_IFSOCK:
            printf("s");
            break;
        case __S_IFLNK:
            printf("l");
            break;
        case __S_IFREG:
            printf("-");
            break;
        case __S_IFBLK:
            printf("b");
            break;
        case __S_IFDIR:
            printf("d");
            break;
        case __S_IFCHR:
            printf("c");
            break;
        case __S_IFIFO:
            printf("p");
            break;
        default:
            ;
    }

    printf("%s", (mystat.st_mode & S_IRWXU) & S_IRUSR ? "r" : "-");
    printf("%s", (mystat.st_mode & S_IRWXU) & S_IWUSR ? "w" : "-");
    printf("%s", (mystat.st_mode & S_IRWXU) & S_IXUSR ? "x" : "-");

    printf("%s", (mystat.st_mode & S_IRWXG) & S_IRGRP ? "r" : "-");
    printf("%s", (mystat.st_mode & S_IRWXG) & S_IWGRP ? "w" : "-");
    printf("%s", (mystat.st_mode & S_IRWXG) & S_IXGRP ? "x" : "-");

    printf("%s", (mystat.st_mode & S_IRWXO) & S_IROTH ? "r" : "-");
    printf("%s", (mystat.st_mode & S_IRWXO) & S_IWOTH ? "w" : "-");
    printf("%s", (mystat.st_mode & S_IRWXO) & S_IXOTH ? "x" : "-");

    printf(" %lu ", mystat.st_nlink);

    struct passwd *mypasswd = getpwuid(mystat.st_uid);
    printf("%s ", mypasswd->pw_name);

    struct group *mygroup = getgrgid(mystat.st_gid);
    printf("%s ", mygroup->gr_name);

    printf("%lu ", mystat.st_size);

    time_t time = mystat.st_ctime;
    struct tm *t = localtime(&time);

    printf("%4d年%02d月%02d日 %02d:%02d:%02d ",
            t->tm_year + 1900,
            t->tm_mon + 1,
            t->tm_mday,
            t->tm_hour,
            t->tm_min,
            t->tm_sec
            );

    printf("%s", file_name);

    putchar('\n');
}

